/**
 * Copyright 2016 JustWayward Team
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ecy.quadratic.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ecy.quadratic.R;
import com.ecy.quadratic.adapter.CommunityCommentListViewAdapter;
import com.ecy.quadratic.adapter.CommunityGridViewAdapter;
import com.ecy.quadratic.beans.Comment;
import com.ecy.quadratic.beans.Community;
import com.ecy.quadratic.beans.PageInfo;
import com.ecy.quadratic.component.DaggerCommunityMainComponent;
import com.ecy.quadratic.manager.EventManager;
import com.ecy.quadratic.manager.LikeManager;
import com.ecy.quadratic.manager.LoginManager;
import com.ecy.quadratic.photopicker.PhotoPreview;
import com.ecy.quadratic.reader.base.BaseActivity;
import com.ecy.quadratic.reader.component.AppComponent;
import com.ecy.quadratic.reader.utils.FormatUtils;
import com.ecy.quadratic.reader.utils.ScreenUtils;
import com.ecy.quadratic.reader.utils.ToastUtils;
import com.ecy.quadratic.ui.contract.CommentLikeContract;
import com.ecy.quadratic.ui.presenter.CommunityCommentPresenter;
import com.ecy.quadratic.widget.ScrollGridView;
import com.ecy.quadratic.widget.SwipeRefreshView;
import com.yuyh.easyadapter.glide.GlideCircleTransform;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by lfh on 2016/8/6.
 */
public class CommunityDetailActivity extends BaseActivity implements CommentLikeContract.View {

    public static final String COMMUNITY_ID = "community";
    @Bind(R.id.community_detail_swipe_refreshview)
    SwipeRefreshView mSwipeRefreshView;
    @Bind(R.id.comment_listview)
    ListView mCommentListView;
    @Bind(R.id.community_detail_llt)
    LinearLayout lltBottom;
    @Bind(R.id.community_detail_edit_rlt)
    RelativeLayout rltEditBottom;
    @Bind(R.id.et_post_comment)
    EditText etPostComment;
    @Bind(R.id.tv_post_comment)
    TextView tvPostComment;
    @Bind(R.id.comment_num_tv)
    TextView mCommentNumTV;
    @Bind(R.id.like_iv)
    ImageView mLikeIV;

    @Inject
    CommunityCommentPresenter mPresenter;
    CommunityGridViewAdapter mAdapter;
    CommunityCommentListViewAdapter mCommentAdapter;

    List<Comment> mList;

    private Community mCommunity;

    private int mCurrentPage = 0;
    private int mTotalPage = 0;
    private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            mPresenter.refresh(mCommunity.id, "1");
        }
    };
    private SwipeRefreshView.OnLoadListener mOnLoadListener = new SwipeRefreshView.OnLoadListener() {

        @Override
        public void onLoad() {
            mPresenter.loadMore(mCommunity.id, mCurrentPage + 1 + "");
        }
    };

//    @Inject
//    BookDetailPresenter mPresenter;

    public static void startActivity(Context context, Community community) {
        context.startActivity(new Intent(context, CommunityDetailActivity.class)
                .putExtra(COMMUNITY_ID, community));
    }

    private void initInfoImages(ScrollGridView imageGridView, final CommunityGridViewAdapter adapter, final ArrayList<String> imgspaths) {
        int wh = (ScreenUtils.getScreenWidth() - ScreenUtils.dpToPxInt(36)) / 3;
        int itemWidth = wh;
        int itemHeight = wh;
        int gridViewWidth = 0;
        switch (imgspaths.size()) {
            case 1:
                gridViewWidth = 3 * wh + ScreenUtils.dpToPxInt(5) * 2;
                imageGridView.setNumColumns(1);
                itemWidth = gridViewWidth;
                itemHeight = itemWidth * 1 / 2;
                break;
            case 2:
            case 4:
                gridViewWidth = 2 * wh + ScreenUtils.dpToPxInt(5);
                imageGridView.setNumColumns(2);
                break;
            case 3:
            case 5:
            case 6:
                gridViewWidth = wh * 3 + ScreenUtils.dpToPxInt(5) * 2;
                imageGridView.setNumColumns(3);
                break;
            default:
                gridViewWidth = wh * 3 + ScreenUtils.dpToPxInt(5) * 2;
                imageGridView.setNumColumns(3);
                break;

        }
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(gridViewWidth, RelativeLayout.LayoutParams.WRAP_CONTENT);
        imageGridView.setLayoutParams(lp);
        adapter.updateData(imgspaths, itemWidth, itemHeight);
        imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                PhotoPreview.builder()
                        .setShowDeleteButton(false)
                        .setPhotos(imgspaths)
                        .setCurrentItem(arg2)
                        .start(CommunityDetailActivity.this);
//					CommunityDetailActivity.startActivity(mContext,adapter.getItem(arg2));
//					Toast.makeText(mContext, "选择了"+adapter.getItem(arg2)+"图片", Toast.LENGTH_LONG).show();
//					Toast.makeText(mContext, "选择了"+(arg2+1)+"图片", Toast.LENGTH_LONG).show();
            }
        });


    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_community_detail;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerCommunityMainComponent.builder()
                .appComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void initToolBar() {
        mCommonToolbar.setNavigationIcon(R.drawable.ab_back);
        mCommonToolbar.setTitle("正文");
    }

    @Override
    public void initData() {
        mList = new ArrayList<>();
        mCommunity = (Community) getIntent().getSerializableExtra(COMMUNITY_ID);
        mAdapter = new CommunityGridViewAdapter(mContext);
        mCommentAdapter = new CommunityCommentListViewAdapter(mContext, mList);
    }

    @Override
    public void configViews() {
        mSwipeRefreshView.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mSwipeRefreshView.setColorSchemeResources(R.color.hobby_theme_color, R.color.hobby_theme_color, R.color.hobby_theme_color);
        mSwipeRefreshView.setOnRefreshListener(mOnRefreshListener);
        mSwipeRefreshView.setOnLoadListener(mOnLoadListener);


        View view = LayoutInflater.from(mContext).inflate(R.layout.community_detail_header, null);
        ImageView userPhotoIV = (ImageView) view.findViewById(R.id.community_user_portrait_iv);
//        @Bind(R.id.community_user_nickname_tv)
        TextView nicknameTV = (TextView) view.findViewById(R.id.community_user_nickname_tv);
//        @Bind((R.id.community_item_time_tv))
        TextView timeTV = (TextView) view.findViewById(R.id.community_item_time_tv);
//        @Bind(R.id.community_item_title_tv)
        TextView contentTV = (TextView) view.findViewById(R.id.community_item_title_tv);
//        @Bind(R.id.community_gridview)
        ScrollGridView imagesGV = (ScrollGridView) view.findViewById(R.id.community_gridview);

        mCommentListView.addHeaderView(view);
        mCommentListView.setAdapter(mCommentAdapter);
        mSwipeRefreshView.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshView.setRefreshing(true);
                mOnRefreshListener.onRefresh();
            }
        });
        imagesGV.setAdapter(mAdapter);
        String name = null, time = null, content = null, headpath = null;
        ArrayList<String> contentimages = null;
        if (mCommunity != null) {
            if (mCommunity.userBean != null) {
                name = mCommunity.userBean.nickname;
                headpath = mCommunity.userBean.portrait;
            }
            time = mCommunity.createtime;
            content = mCommunity.content;
            if (mCommunity.imagesBean != null) {
                contentimages = mCommunity.imagesBean;
            }
        }

        if (!TextUtils.isEmpty(name)) {
            nicknameTV.setText(name);
        }

        if (contentimages != null) {
            imagesGV.setVisibility(View.VISIBLE);
            initInfoImages(imagesGV, mAdapter, contentimages);
        } else {
            imagesGV.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(time)) {
            timeTV.setText(FormatUtils.getDescriptionTimeFromDateString(time));
        }

        if (!TextUtils.isEmpty(content)) {
            contentTV.setText(content);
            Linkify.addLinks(contentTV, Linkify.WEB_URLS);
            contentTV.setVisibility(View.VISIBLE);
        } else {
            contentTV.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(headpath)) {
            Glide.with(mContext).load(headpath).placeholder(R.drawable.cover_default_square).transform(new GlideCircleTransform(mContext)).into(userPhotoIV);
        }
        if (LikeManager.getInstance().isCollected(mCommunity.id)) {
            mLikeIV.setImageResource(R.drawable.like_normal_pressed);
            mLikeIV.setClickable(false);
        } else {
            mLikeIV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LikeManager.getInstance().add(mCommunity.id);
                    mLikeIV.setImageResource(R.drawable.like_normal_pressed);
                    mLikeIV.setClickable(false);
                    mPresenter.postLike(mCommunity.id);
                }
            });
        }
        mPresenter.attachView(this);
//        mPresenter.getBookDetail(bookId);
//        mPresenter.getHotReview(bookId);
//        mPresenter.getRecommendBookList(bookId, "3");
    }

    @OnClick(R.id.community_detail_llt)
    public void onBottomClick() {
        rltEditBottom.setVisibility(View.VISIBLE);
        lltBottom.setVisibility(View.GONE);
        etPostComment.requestFocus();
        etPostComment.requestFocusFromTouch();
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(etPostComment, InputMethodManager.SHOW_FORCED);
    }

    @OnClick(R.id.community_detail_edit_rlt)
    public void onEditClick() {
        rltEditBottom.setVisibility(View.GONE);
        lltBottom.setVisibility(View.VISIBLE);
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(etPostComment.getWindowToken(), 0);
    }

    @OnClick(R.id.title_back_iv)
    public void back() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
    }

    @Override
    public void showRefreshList(PageInfo<Comment> pageInfo) {

        if (pageInfo != null) {
            if (pageInfo.total != 0) {
                mCommentNumTV.setText(pageInfo.total + "条评论");
            }
            mCurrentPage = pageInfo.pageNum;
            mTotalPage = pageInfo.pages;
            mList.clear();
            mCommentAdapter.notifyDataSetChanged();
            mList.addAll(pageInfo.list);
            mCommentAdapter.notifyDataSetChanged();
            if (mList.size() > 0) {
                mCommentListView.post(new Runnable() {
                    @Override
                    public void run() {
                        mCommentListView.smoothScrollToPosition(0);
                    }
                });
            }
        }
    }

    @Override
    public void showLoadMoreList(PageInfo<Comment> pageInfo) {
        if (pageInfo != null && mCurrentPage != pageInfo.pageNum) {
            mCurrentPage = pageInfo.pageNum;
            mTotalPage = pageInfo.pages;
            mList.addAll(pageInfo.list);
            mCommentAdapter.notifyDataSetChanged();
        }
    }

    @OnClick(R.id.tv_post_comment)
    public void postComment() {
        mPresenter.postComment(mCommunity.id, "", LoginManager.getInstance().getUserJson(), etPostComment.getText().toString());
    }

    @Override
    public void postCommentSuccesful() {
        etPostComment.setText("");
        ToastUtils.getSingleToast("发表评论成功", Toast.LENGTH_SHORT).show();
        onEditClick();
        mSwipeRefreshView.setRefreshing(true);
        mOnRefreshListener.onRefresh();
        EventManager.updateCommentNum(mCommunity.id);
    }

    @Override
    public void postLikeSuccessful() {

    }

    @Override
    public void showError() {
        mSwipeRefreshView.setRefreshing(false);
        mSwipeRefreshView.setLoading(false, true);
    }

    @Override
    public void complete() {
        mSwipeRefreshView.setRefreshing(false);
        mSwipeRefreshView.setLoading(false);
    }
}
